package xyz.jcat.biz.admin.auth;

import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import xyz.jcat.auth.token.AccessTokenUtils;
import xyz.jcat.auth.token.UserTokenDto;
import xyz.jcat.common.web.Resp;
import xyz.jcat.security.UserRoleAuthenticationToken;
import xyz.jcat.web.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {

    private static final long ACCESS_TOKEN_CACHE_TIME_OUT = 60 * 60 * 2;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        UserRoleAuthenticationToken authenticationToken = (UserRoleAuthenticationToken) authentication;
        UserTokenDto userToken = new UserTokenDto(authenticationToken.getUserId(), authenticationToken.getRoleIds());
        //删除过去登录记录
        AccessTokenUtils.removeAccessToken(authenticationToken.getUserId());
        //生成新的accessToken
        String token = AccessTokenUtils.generateAccessToken(userToken, ACCESS_TOKEN_CACHE_TIME_OUT);
        WebUtils.writeJson(response, Resp.ok(token));
    }
}
